﻿// Decompiled with JetBrains decompiler
// Type: DnProcessSimulateCommands.TcCommands.CUiAWCMfgSearchWindow
// Assembly: DnProcessSimulateCommands, Version=2402.0.0.890, Culture=neutral, PublicKeyToken=null
// MVID: A885D881-AEDF-447E-852A-6F13102E089C
// Assembly location: C:\Program Files\Tecnomatix_2402\eMPower\DotNetCommands\DnProcessSimulateCommands.dll

using ActiveWorkspaceHosting;
using EngineeringInternalExtension;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web.Script.Serialization;
using System.Windows;
using System.Windows.Forms;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using Tecnomatix.Engineering;
using Tecnomatix.Engineering.Ui.WPF;
using Tecnomatix.Engineering.Utilities;


namespace DnProcessSimulateCommands.TcCommands;

public class CUiAWCMfgSearchWindow : AWCTeamcenterNavigator
{
  private bool m_ignoreSelectionChange;

  public CUiAWCMfgSearchWindow(CApAWCHostSessionManager hostManager)
    : base(hostManager)
  {
    ((FrameworkElement) this).MinWidth = 428.0;
    ((FrameworkElement) this).MinHeight = 690.0;
    ((FrameworkElement) this).MaxWidth = 1280.0;
    this.ShouldAutoPosition = true;
    ((Window) this).Icon = this.GetIconImage("pack://application:,,,/DnProcessSimulateCommands;component/TcCommands/TcNavigator/Images/SearchMfgs.ico");
    TxCommandsManager.EnableBlankDisplayInSemiModalMode = true;
    this.EnrolServicesForAvailabilityNotification();
  }

  private bool IsValidFrameSize(double value)
  {
    return !double.IsNaN(value) && !double.IsInfinity(value) && value > 0.0;
  }

  protected virtual void OnSourceInitialized(EventArgs e)
  {
    double num1 = 420.0;
    double num2 = 670.0;
    double num3 = ((FrameworkElement) this).ActualWidth - this.m_grid.ActualWidth;
    if (this.IsValidFrameSize(num3))
    {
      double num4 = ((FrameworkElement) this).ActualHeight - this.m_grid.ActualHeight;
      if (this.IsValidFrameSize(num4))
      {
        ((FrameworkElement) this).MinWidth = num1 + num3;
        ((FrameworkElement) this).MinHeight = num2 + num4;
      }
    }
    base.OnSourceInitialized(e);
    object obj;
    TxWindowSettings.RestoreWindowValue((TxWindow) this, "Width", ref obj);
    if (obj != null)
      return;
    // ISSUE: explicit non-virtual call
    __nonvirtual (((FrameworkElement) this).Width) = ((FrameworkElement) this).MinWidth;
    // ISSUE: explicit non-virtual call
    __nonvirtual (((FrameworkElement) this).Height) = ((FrameworkElement) this).MinHeight;
  }

  private void EnrolServicesForAvailabilityNotification()
  {
    this.m_hostControl.EnrolServiceForAvailabilityNotification(new TxBaseServiceDescriptor("com.siemens.splm.tcmaccess.SelectMfgsInSearchResult.client", "_2019_05"));
  }

  private ImageSource GetIconImage(string uriPath)
  {
    Uri uriSource = new Uri(uriPath, UriKind.Absolute);
    return uriSource == (Uri) null ? (ImageSource) null : (ImageSource) new BitmapImage(uriSource);
  }

  private CApAWCSearchMFGConnectionManager Manager
  {
    get => this.m_hostManager as CApAWCSearchMFGConnectionManager;
  }

  protected override void RegisterManagerServicesAndEventsInternal()
  {
    base.RegisterManagerServicesAndEventsInternal();
    this.Manager.MfgsLoaded += new EventHandler<CApAWCMfgsLoadedEventArgs>(this.CUiAWCMfgSearchWindow_MfgsLoaded);
    this.Manager.SelectMfgsInPS += new EventHandler<CApAWCSelectMfgsInPSEventArgs>(this.CUiAWCMfgSearchWindow_SelectMfgsInPS);
    this.Manager.MfgCache.MfgVisibilityUpdate += new EventHandler<CApAWCMfgVisibilityUpdateEventArgs>(this.CUiAWCMfgSearchWindow_MfgVisibilityUpdateInTCMA);
    this.m_hostControl.ServicesAvailable += new EventHandler<TxAWCServicesAvailableEventArgs>(this.CUiAWCMfgSearchWindow_ServicesAvailable);
    this.RegisterSelectionEvents();
  }

  protected override void UnitializeInternal()
  {
    TxCommandsManager.EnableBlankDisplayInSemiModalMode = false;
    this.UnRegisterSelectionEvents();
    this.Manager.MfgsLoaded -= new EventHandler<CApAWCMfgsLoadedEventArgs>(this.CUiAWCMfgSearchWindow_MfgsLoaded);
    this.Manager.SelectMfgsInPS -= new EventHandler<CApAWCSelectMfgsInPSEventArgs>(this.CUiAWCMfgSearchWindow_SelectMfgsInPS);
    this.Manager.MfgCache.MfgVisibilityUpdate += new EventHandler<CApAWCMfgVisibilityUpdateEventArgs>(this.CUiAWCMfgSearchWindow_MfgVisibilityUpdateInTCMA);
    this.m_hostControl.ServicesAvailable -= new EventHandler<TxAWCServicesAvailableEventArgs>(this.CUiAWCMfgSearchWindow_ServicesAvailable);
    this.Manager.MfgCache.Clear();
    this.Manager.ClearPreview();
    base.UnitializeInternal();
  }

  private void CUiAWCMfgSearchWindow_MfgsLoaded(object sender, CApAWCMfgsLoadedEventArgs e)
  {
    TxTcImportResultEx result = e.Result;
    if (result != null)
    {
      IEnumerable<TxTcResultObjectDataEx> loadedObjects = result.LoadedObjects;
      IEnumerable<TxTcResultObjectDataEx> existingObjects = result.ExistingObjects;
      IEnumerable<TxTcResultObjectDataEx> resultObjectDataExes = loadedObjects.Concat<TxTcResultObjectDataEx>(existingObjects);
      IEnumerable<ITxObject> itxObjects = resultObjectDataExes.Select<TxTcResultObjectDataEx, ITxObject>((Func<TxTcResultObjectDataEx, ITxObject>) (x => x.Object));
      this.Manager.CacheLoadedMfgs(itxObjects);
      if (!e.IsPreview)
      {
        this.Manager.UpdateVisibilityInTCMAAfterLoad(resultObjectDataExes);
        this.EmphasizeLoadedMfgs(loadedObjects.Select<TxTcResultObjectDataEx, string>((Func<TxTcResultObjectDataEx, string>) (x => x.Uid)));
      }
      else if (this.Manager.SelectionSynchronizationSupported)
      {
        this.Manager.CachePreviewedMfgsBomLineUids(resultObjectDataExes);
        this.Manager.UpdateVisibilityInPSAfterPreview(existingObjects, e.MfgsToLoad);
        itxObjects = this.Manager.GetMfgsSelectedInTCMA(resultObjectDataExes, e.MfgsToLoad);
      }
      this.SelectMfgs(itxObjects);
      TxApplication.RefreshDisplay();
      if (result.NotLoadedObjects.Count<TxTcResultObjectDataEx>() <= 0)
        return;
      this.ShowErrorLog(e.MfgsToLoad, result.NotLoadedObjects, e.IsPreview);
    }
    else if (e.IsProcessOrOperationLoaded)
    {
      int num1 = (int) TxMessageBox.ShowModal(DnProcessSimulateCommands.TcCommands.TcNavigator.StringTable.SEARCH_MFG_LOAD_FAILED, DnProcessSimulateCommands.TcCommands.TcNavigator.StringTable.SEARCH_MFG_COMMAND_NAME, MessageBoxButtons.OK, MessageBoxIcon.Hand);
    }
    else
    {
      int num2 = (int) TxMessageBox.ShowModal(DnProcessSimulateCommands.TcCommands.TcNavigator.StringTable.SEARCH_MFG_PROCESS_MISSING_ERROR, DnProcessSimulateCommands.TcCommands.TcNavigator.StringTable.SEARCH_MFG_COMMAND_NAME, MessageBoxButtons.OK, MessageBoxIcon.Hand);
    }
  }

  private void SelectMfgs(IEnumerable<ITxObject> mfgsToSelect)
  {
    if (mfgsToSelect == null || mfgsToSelect.Count<ITxObject>() <= 0)
      return;
    TxObjectList<ITxObject> txObjectList1 = new TxObjectList<ITxObject>(mfgsToSelect);
    TxObjectList txObjectList2 = new TxObjectList();
    ((TxObjectList<ITxObject>) txObjectList2).AddRange(txObjectList1);
    this.m_ignoreSelectionChange = true;
    TxApplication.ActiveSelection.SetItems(txObjectList2);
  }

  private void EmphasizeLoadedMfgs(IEnumerable<string> loadedUids)
  {
    if (loadedUids == null || loadedUids.Count<string>() <= 0)
      return;
    TxBaseServiceDescriptor serviceDescriptor = new TxBaseServiceDescriptor("com.siemens.splm.client.processsimulate.hosted.services.refresh.ClientGetLoadedMfgsService", "_2014_07");
    string str = TxJsonSerializationHelper.DataContractJsonSerializer<TxRequestLoadedMfgsMsg>(new TxRequestLoadedMfgsMsg()
    {
      MfgIds = loadedUids.ToList<string>()
    });
    try
    {
      this.m_hostControl.InvokeWebEvent(serviceDescriptor, str);
    }
    catch (Exception ex)
    {
      TxApplication.LogWriter.WriteExceptionLine(ex);
    }
  }

  private void ShowErrorLog(
    IEnumerable<ITxMfgInfo> mfgsToLoad,
    IEnumerable<TxTcResultObjectDataEx> notLoadedObjects,
    bool isPreview)
  {
    Hashtable hashtable1 = new Hashtable();
    Hashtable hashtable2 = new Hashtable();
    bool flag = false;
    if (notLoadedObjects != null)
    {
      List<string> stringList1 = new List<string>();
      foreach (TxTcResultObjectDataEx notLoadedObject1 in notLoadedObjects)
      {
        TxTcResultObjectDataEx notLoadedObject = notLoadedObject1;
        string title = mfgsToLoad.First<ITxMfgInfo>((Func<ITxMfgInfo, bool>) (x => x.UID == notLoadedObject.Uid)).Title;
        stringList1.Add(title);
      }
      if (stringList1.Count > 0)
      {
        hashtable2.Add((object) DnProcessSimulateCommands.TcCommands.TcNavigator.StringTable.SEARCH_MFG_NONLOADED_OBJECTS_ERROR, (object) stringList1.ToArray());
        List<string> stringList2 = new List<string>();
        flag = true;
      }
    }
    if (!flag)
      return;
    TxErrorWindow.ShowDialog(DnProcessSimulateCommands.TcCommands.TcNavigator.StringTable.SEARCH_MFG_COMMAND_NAME, isPreview ? DnProcessSimulateCommands.TcCommands.TcNavigator.StringTable.SEARCH_MFG_PREVIEW_ERROR_WINDOW_TEXT : DnProcessSimulateCommands.TcCommands.TcNavigator.StringTable.SEARCH_MFG_ERROR_WINDOW_TEXT, hashtable2, hashtable1, true);
  }

  private void SelectMfgsInTCMA()
  {
    if (!this.m_ignoreSelectionChange && this.Manager.SelectionSynchronizationSupported)
    {
      List<string> currentSelection = this.Manager.GetMfgsFromCurrentSelection();
      TxBaseServiceDescriptor serviceDescriptor = new TxBaseServiceDescriptor("com.siemens.splm.tcmaccess.SelectMfgsInSearchResult.client", "_2019_05");
      string str = TxJsonSerializationHelper.DataContractJsonSerializer<TxClientSelectMfgsInSearchResultMsg>(new TxClientSelectMfgsInSearchResultMsg()
      {
        MfgIds = currentSelection.ToList<string>()
      });
      try
      {
        this.m_hostControl.InvokeWebEvent(serviceDescriptor, str);
      }
      catch (Exception ex)
      {
        TxApplication.LogWriter.WriteExceptionLine(ex);
      }
    }
    this.m_ignoreSelectionChange = false;
  }

  private void CUiAWCMfgSearchWindow_SelectMfgsInPS(object sender, CApAWCSelectMfgsInPSEventArgs e)
  {
    IEnumerable<ITxObject> mfgsToSelect = e.MfgsToSelect;
    if (mfgsToSelect == null)
      return;
    if (mfgsToSelect.Count<ITxObject>() > 0)
    {
      this.SelectMfgs(mfgsToSelect);
    }
    else
    {
      this.m_ignoreSelectionChange = true;
      TxApplication.ActiveSelection.Clear();
    }
  }

  private void CUiAWCMfgSearchWindow_MfgVisibilityUpdateInTCMA(
    object sender,
    CApAWCMfgVisibilityUpdateEventArgs e)
  {
    if (!this.Manager.SelectionSynchronizationSupported)
      return;
    Dictionary<string, bool> mfgsToUpdate = e.MfgsToUpdate;
    TxBaseServiceDescriptor serviceDescriptor = new TxBaseServiceDescriptor("com.siemens.splm.tcmaccess.MfgVisibilityUpdate.client", "_2019_06");
    string str = new JavaScriptSerializer().Serialize((object) new TxMfgVisibilityUpdateMsg()
    {
      MfgVisibilityUpdateData = mfgsToUpdate
    });
    try
    {
      this.m_hostControl.InvokeWebEvent(serviceDescriptor, str);
    }
    catch (Exception ex)
    {
      TxApplication.LogWriter.WriteExceptionLine(ex);
    }
  }

  private void CUiAWCMfgSearchWindow_ServicesAvailable(
    object sender,
    TxAWCServicesAvailableEventArgs e)
  {
    TxBaseServiceDescriptor serviceDescriptor = new TxBaseServiceDescriptor("com.siemens.splm.tcmaccess.SelectMfgsInSearchResult.client", "_2019_05");
    if (!e.Contains(serviceDescriptor))
      return;
    try
    {
      this.Manager.SelectionSynchronizationSupported = true;
      this.Manager.InitMfgCache();
    }
    catch (Exception ex)
    {
      TxApplication.LogWriter.WriteExceptionLine(ex);
    }
  }

  public void RegisterSelectionEvents()
  {
    try
    {
      TxSelection activeSelection = TxApplication.ActiveSelection;
      activeSelection.ItemsAdded += new TxSelection_ItemsAddedEventHandler(this.OnSelectionAdded);
      activeSelection.ItemsRemoved += new TxSelection_ItemsRemovedEventHandler(this.OnSelectionRemoved);
      activeSelection.ItemsSet += new TxSelection_ItemsSetEventHandler(this.OnSelectionSet);
      activeSelection.Cleared += new TxSelection_ClearedEventHandler(this.OnSelectionCleared);
    }
    catch (Exception ex)
    {
    }
  }

  public void UnRegisterSelectionEvents()
  {
    try
    {
      TxSelection activeSelection = TxApplication.ActiveSelection;
      activeSelection.ItemsAdded -= new TxSelection_ItemsAddedEventHandler(this.OnSelectionAdded);
      activeSelection.ItemsRemoved -= new TxSelection_ItemsRemovedEventHandler(this.OnSelectionRemoved);
      activeSelection.ItemsSet -= new TxSelection_ItemsSetEventHandler(this.OnSelectionSet);
      activeSelection.Cleared -= new TxSelection_ClearedEventHandler(this.OnSelectionCleared);
    }
    catch (Exception ex)
    {
    }
  }

  private void OnSelectionAdded(object sender, TxSelection_ItemsAddedEventArgs e)
  {
    this.SelectMfgsInTCMA();
  }

  private void OnSelectionRemoved(object sender, TxSelection_ItemsRemovedEventArgs e)
  {
    this.SelectMfgsInTCMA();
  }

  private void OnSelectionSet(object sender, TxSelection_ItemsSetEventArgs e)
  {
    this.SelectMfgsInTCMA();
  }

  private void OnSelectionCleared(object sender, TxSelection_ClearedEventArgs e)
  {
    this.SelectMfgsInTCMA();
  }
}
